from datetime import datetime, timezone
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required
from config import Config
from model import Homework, StudentCourse, SubmissionHomework, User, Course
from extension import db
from werkzeug.utils import secure_filename
from flask_jwt_extended import get_jwt_identity
from views.user import student_required, admin_required, assistant_required
import os
from flask import send_from_directory, jsonify

import os

homework_bp = Blueprint('homework', __name__)


# 文件存放目录


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in Config.ALLOWED_EXTENSIONS


@homework_bp.route('/undo_count/<student_id>', methods=['GET'])
@jwt_required()
def get_incomplete_homework_count(student_id):
    # Count the number of incomplete submissions for the student
    #incomplete_count = SubmissionHomework.query.filter_by(student_id=student_id, status='incomplete').count()

    incomplete_count = SubmissionHomework.query.filter_by(student_id=student_id, status=False).count()
    return jsonify({'incomplete_count': incomplete_count}), 200


@homework_bp.route('/undo_course/<student_id>', methods=['GET'])
@jwt_required()
def get_incomplete_homework_courses(student_id):
    # Get courses with incomplete homework for the student
    courses = db.session.query(StudentCourse).filter_by(student_id=student_id).all()


    incomplete_courses = []

    for course in courses:
        homework = Homework.query.filter_by(course_id=course.course_id).all()
        course_info = Course.query.filter_by(course_id=course.course_id).first()
        for hw in homework:
            if SubmissionHomework.query.filter_by(student_id=student_id, homework_id=hw.homework_id, status=0).first():
                incomplete_courses.append({'course_id': course_info.course_id, 'course_name': course_info.course_name})
                break

    return jsonify(incomplete_courses), 200


@homework_bp.route('/create/<course_id>', methods=['POST'])
@jwt_required()
@admin_required
def create_homework(course_id):
    data = request.json
    print(data)
    file = None
    if 'file' in data:
        file = data['file']
    file_path = None

    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        file_path = os.path.join(Config.HOMEWORKS_FOLDER, filename)
        file.save(file_path)  # 保存文件到服务器指定路径

    # 从请求数据中获取总分
    total_score = data.get('total_score', 100)  # 如果未提供总分，则默认为100

    new_homework = Homework(
        course_id=course_id,
        title=data['title'],
        homework_description=data['description'],
        start_time=data['start_time'],
        end_time=data['end_time'],
        status=True,
        file_path=file_path,
        total_score=total_score  # 保存总分
    )
    db.session.add(new_homework)
    db.session.commit()
    return jsonify({'homework_id': new_homework.homework_id}), 201


@homework_bp.route('/assign_homework/<course_id>', methods=['POST'])
@jwt_required()
@admin_required
def assign_homework(course_id):
    data = request.json
    student_ids = data['student_id']
    homework_id = data['homework_id']
    print(data)
    #TODO 修改grade
    for student_id in student_ids:
        new_submission = SubmissionHomework(
            student_id=student_id,
            homework_id=homework_id,
            file_path=None,
            status=False
        )
        db.session.add(new_submission)
    db.session.commit()
    return jsonify({'message': 'Homework created successfully.'}), 201


@homework_bp.route('/view/<course_id>', methods=['GET'])
@jwt_required()
def view_homework(course_id):
    # 获取当前用户身份
    current_student_id = get_jwt_identity()
    print(current_student_id)
    uid = current_student_id.get('uid')

    # 查询该课程下的所有作业
    homework = Homework.query.filter_by(course_id=course_id).all()

    if not homework:
        return jsonify({'message': 'No homework found for this course.'}), 201

    homework_list = []
    for hw in homework:
        # 查询该学生提交的作业记录，获取分数
        submission = SubmissionHomework.query.filter_by(student_id=uid,
                                                        homework_id=hw.homework_id).first()
        if not submission:
            continue

        homework_data = {
            'homework_id': hw.homework_id,
            'title': hw.title,
            'description': hw.homework_description,
            'start_time': hw.start_time,
            'end_time': hw.end_time,
            'grade': submission.grade,  # 包含分数
            'submission_status': submission.status,  # 提交状态
            'allow_delete': submission.allow_delete,
            'total_score': hw.total_score  # 添加总分字段
        }

        homework_list.append(homework_data)

    return jsonify(homework_list), 200



@homework_bp.route('/submit/<student_id>', methods=['POST'])
@jwt_required()
@student_required
def submit_homework(student_id):
    if 'homework_id' not in request.form:
        return jsonify({'message': 'Missing homework ID.'}), 400

    homework_id = request.form['homework_id']
    # 处理文本内容
    homework_text = request.form.get('homework_text', None)
    # 处理文件上传
    file = request.files.get('file', None)
    file_path = None

    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        file_path = os.path.join(Config.SUBMITWORKS_FOLDER, filename)
        file.save(file_path)  # 保存文件到服务器指定路径

    submission = SubmissionHomework.query.filter_by(student_id=student_id, homework_id=homework_id).first()

    if submission:
        # 更新已有提交记录
        submission.file_path = file_path if file else submission.file_path
        submission.status = True
        submission.grade = 0  # 提交后等待批改，分数设为0
        if homework_text:
            submission.set_homework_text(homework_text)
    else:
        # 创建新的提交记录
        submission = SubmissionHomework(
            student_id=student_id,
            homework_id=homework_id,
            file_path=file_path,
            status=True,  # 已提交状态
            grade=0
        )
        if homework_text:
            submission.set_homework_text(homework_text)

        db.session.add(submission)

    # 如果有文本内容，保存作业文本
    db.session.commit()
    return jsonify({'message': 'Homework submitted successfully.'}), 201


@homework_bp.route('/download/<course_id>', methods=['GET'])
@jwt_required()
def download_homework(course_id):
    # 查询该课程下的所有作业
    homework = Homework.query.filter_by(course_id=course_id).all()
    if not homework:
        return jsonify({'message': 'No homework found for this course.'}), 404

    # 生成下载链接
    download_links = []
    for hw in homework:
        submission = SubmissionHomework.query.filter_by(homework_id=hw.homework_id).first()
        if submission and submission.file_path:  # 检查作业是否有附件
            download_links.append({
                'homework_id': hw.homework_id,
                'title': hw.title,
                'download_url': f'/download/homework/{hw.homework_id}'
            })

    if not download_links:
        return jsonify({'message': 'No attachments found for this course.'}), 404

    return jsonify(download_links), 200


# 具体的下载接口
@homework_bp.route('/download/homework/<homework_id>', methods=['GET'])
@jwt_required()
def download_file(homework_id):
    submission = SubmissionHomework.query.filter_by(homework_id=homework_id).first()
    if not submission or not submission.file_path:
        return jsonify({'message': 'File not found.'}), 404

    # 提取文件路径和文件名
    file_path = submission.file_path
    directory = os.path.dirname(file_path)
    filename = os.path.basename(file_path)

    # 使用 send_from_directory 来发送文件
    return send_from_directory(directory, filename, as_attachment=True)


@homework_bp.route('/submissions/<course_id>', methods=['GET'])
@jwt_required()
@admin_required
def view_homework_grades(course_id):
    homework_id = request.args.get('homework_id')
    # 获取该课程下指定作业的所有提交
    submissions = (
        db.session.query(SubmissionHomework, User.name)
        .join(User, SubmissionHomework.student_id == User.student_id)
        .filter(SubmissionHomework.homework_id == homework_id)
        .all()
    )

    if not submissions:
        return jsonify({'message': 'No submissions found for this course.'}), 200

    graded_submissions = [{
        'submission_id': sub.submissionH_id,  # 提交 ID
        'student_id': sub.student_id,  # 学生 ID
        'student_name': name,  # 学生名字
        'homework_id': sub.homework_id,  # 作业 ID
        'grade': sub.grade,  # 成绩
        'status': sub.status  # 提交状态
    } for sub, name in submissions]

    return jsonify(graded_submissions), 200



@homework_bp.route('/grade/<submission_id>', methods=['POST'])
@jwt_required()
@admin_required
def grade_submission(submission_id):
    data = request.json
    grade = data.get('grade')

    # 查询提交记录
    submission = SubmissionHomework.query.filter_by(submissionH_id=submission_id).first()
    if not submission:
        return jsonify({'message': 'Submission not found.'}), 404

    # 更新评分
    submission.set_grade(grade)
    submission.status = True
    db.session.commit()

    return jsonify({'message': 'Grade updated successfully.'}), 200


#一键上传分数
@homework_bp.route('/upload_grade/<course_id>', methods=['POST'])
@jwt_required()
@admin_required
def upload_grade(course_id):
    data = request.json
    for student_id, grade in data['grades'].items():
        submission = SubmissionHomework.query.filter_by(student_id=student_id,
                                                        homework_id=int(data['homework_id'])).first()
        if submission:
            submission.grade = grade
            submission.status = True
            db.session.commit()
    return jsonify({'message': 'Grades uploaded successfully.'}), 200

@homework_bp.route('/delete_submission/<submission_id>', methods=['POST'])
@jwt_required()
def delete_submission(submission_id):
    # 查询作业提交记录
    submission = SubmissionHomework.query.filter_by(submissionH_id=submission_id).first()

    if not submission:
        return jsonify({'message': 'Submission not found.'}), 404

    # 检查是否允许删除
    if not submission.allow_delete:
        return jsonify({'message': 'Deletion not allowed for this submission.'}), 403

    # 删除文件（如果有附件）
    if submission.file_path:
        try:
            os.remove(submission.file_path)  # 删除文件
        except FileNotFoundError:
            return jsonify({'message': 'File not found on server, but submission will be deleted.'}), 404

    # 删除数据库记录
    submission.status = False
    submission.file_path = None
    db.session.commit()

    return jsonify({'message': 'Submission deleted successfully.'}), 200


@homework_bp.route('/check_homework_status/<homework_id>', methods=['GET'])
@jwt_required()
def check_homework_status(homework_id):
    homework_id = int(homework_id)
    # 查询该作业
    homework = Homework.query.filter_by(homework_id=homework_id).first()

    if not homework:
        return jsonify({'message': 'Homework not found.'}), 404
    # return jsonify({'message': 'Homework found.'}), 200
    # 获取当前时间
    current_time = datetime.now(timezone.utc)
    if homework.end_time:
        homework_end_time = homework.end_time.replace(tzinfo=timezone.utc)
    # 检查是否有截止时间，并判断是否超过end_time
    if homework_end_time and current_time > homework_end_time:
        submissions = SubmissionHomework.query.filter_by(homework_id=homework.homework_id).all()
        for submission in submissions:
            if submission.allow_delete:  # 仅在 allow_delete 为 True 时更新
                submission.allow_delete = False
        db.session.commit()
        return jsonify(
            {'message': 'Homework submission period has ended.', 'can_submit': False, 'can_delete': False}), 403

    # 如果没有超出截止时间
    return jsonify(
        {'message': 'Homework is still within the submission period.', 'can_submit': True, 'can_delete': True}), 200


@homework_bp.route('/get_studentself_submission/<student_id>', methods=['GET'])
@jwt_required()
@student_required
def view_student_submissions(student_id):
    """
    获取指定学生的作业提交情况。
    """
    homework_id = request.args.get('homework_id')
    # 获取该学生提交的所有作业记录
    submissions = SubmissionHomework.query.filter_by(student_id=student_id, homework_id=homework_id).all()
   
    if not submissions:
        return jsonify({'message': 'No submissions found for this student.'}), 404

    submission_list = []
    
    for submission in submissions:
        # 获取作业的详细信息
        homework = Homework.query.filter_by(homework_id=submission.homework_id).first()
        if not homework:
            continue

        submission_data = {
            'submission_text': submission.homework_text,
            'start_time': homework.start_time,
            'end_time': homework.end_time,
            'submission_time': submission.submission_time,  # 提交时间
            'file_path': submission.file_path,  # 提交的文件路径
            'status': submission.status,  # 提交状态
            'grade': submission.grade  # 分数
        }
        submission_list.append(submission_data)
    # return jsonify({'message': 'No submissions found for this student.'}), 200
    return jsonify(submission_list), 200


@homework_bp.route('/upload_file', methods=['GET'])
@jwt_required()
def upload_file():
    if 'file' not in request.files:
        return jsonify({'message': 'No file part.'}), 400

    file = request.files['file']

    if file.filename == '':
        return jsonify({'message': 'No selected file.'}), 400

    if not allowed_file(file.filename):
        return jsonify({'message': 'File type not allowed.'}), 400

    filename = secure_filename(file.filename)
    file_path = os.path.join(Config.SUBMITWORKS_FOLDER, filename)

    # 保存文件
    file.save(file_path)

    # 构造文件的 URL（根据您的 URL 结构）
    file_url = f'/submitworks/{filename}'

    return jsonify({'file_url': file_url}), 201


@homework_bp.route('/submission_detail', methods=['GET'])
@jwt_required()
@admin_required
def view_student_submission():
    # 查询指定作业和学生的提交记录
    data = request.args
    homework_id, student_id = data['homework_id'], data['student_id']

    submission = (
        db.session.query(SubmissionHomework, User.name)
        .join(User, SubmissionHomework.student_id == User.student_id)
        .filter(SubmissionHomework.homework_id == homework_id, SubmissionHomework.student_id == student_id)
        .first()
    )

    if not submission:
        return jsonify({'message': 'No submission found for this student and homework.'}), 404

    sub, student_name = submission

    # 构建返回的 JSON 对象，包含提交作业的详细信息
    submission_info = {
        'submission_id': sub.submissionH_id,
        'student_id': sub.student_id,
        'student_name': student_name,
        'submission_time': sub.submission_time,
        'homework_text': sub.homework_text,
        'file_path': sub.file_path,
        'grade': sub.grade,
        'status': sub.status
    }

    return jsonify(submission_info), 200


@homework_bp.route('/teacher_view_homework_list/<course_id>', methods=['GET'])
@jwt_required()
def view_homework_list(course_id):
    # 获取当前用户身份
    current_student_id = get_jwt_identity()

    # 查询该课程下的所有作业
    homework = Homework.query.filter_by(course_id=course_id).all()

    if not homework:
        return jsonify({'message': 'No homework found for this course.'}), 201

    homework_list = []
    for hw in homework:
        # 查询该学生提交的作业记录，获取分数
        submission_count = SubmissionHomework.query.filter_by(homework_id=hw.homework_id, status=True).count()
        total_count = SubmissionHomework.query.filter_by(homework_id=hw.homework_id).count()

        homework_data = {
            'homework_id': hw.homework_id,
            'title': hw.title,
            'description': hw.homework_description,
            'start_time': hw.start_time,
            'end_time': hw.end_time,
            'status': hw.status,  # 作业状态
            'submission_count': submission_count,
            'total_count': total_count,
            'total_grade': hw.total_score,
            'total_score': hw.total_score  # 添加总分字段

        }

        homework_list.append(homework_data)

    return jsonify(homework_list), 200


@homework_bp.route('/delete_homework/<homework_id>', methods=['POST'])
@jwt_required()
@admin_required
def delete_specific_homework(homework_id):
    """
    删除指定的作业
    :param homework_id: 作业ID
    """
    # 查找指定的作业
    homework = Homework.query.filter_by(homework_id=homework_id).first()
    if not homework:
        return jsonify({'message': 'Homework not found.'}), 404

    # 删除该作业的所有相关提交记录
    submissions = SubmissionHomework.query.filter_by(homework_id=homework_id).all()
    for submission in submissions:
        # 删除文件（如果有附件）
        if submission.file_path:
            try:
                os.remove(submission.file_path)
            except FileNotFoundError:
                pass  # 文件已丢失的情况可忽略

        # db.session.delete(submission)

    # 删除作业文件（如果有附件）
    if homework.file_path:
        try:
            os.remove(homework.file_path)
        except FileNotFoundError:
            pass  # 文件已丢失的情况可忽略

    # 删除作业记录
    # db.session.delete(homework)
    db.session.commit()

    return jsonify({'message': 'Homework deleted successfully.'}), 200
